package com.safone.thirdattendanceservices.dormitory.services.impl;

import com.alibaba.fastjson.JSON;
import com.cqsudu.lightning.boot.exceptions.ServiceSysException;
import com.safone.thirdattendanceservices.configs.ArgsUtil;
import com.safone.thirdattendanceservices.dormitory.services.DormitoryAttendanceDataService;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author xy
 * @date 2020/12/4 20:47
 */
@Component
public class DormitoryAttendanceDataServiceImpl implements DormitoryAttendanceDataService {
  @Autowired private RestTemplate restTemplate;
  @Autowired private ArgsUtil argsUtil;

  private Boolean key = true;

  private Boolean keyMap = true;

  @Override
  public List<Map<String, Object>> findSchool() {
    List<Map> data = (List<Map>) findDormitoryByName().getBody().get("data");
    List<Map> list1 = data.stream().filter(map -> (Integer) map.get("level") == 0).collect(Collectors.toList());
    List<Map<String, Object>> mapList = list1.stream().map(map -> {
      String schoolId = (String) map.get("id");
      String schoolName = (String) map.get("name");
      Map<String, Object> hashMap = new HashMap<>();
      hashMap.put("schoolId", schoolId);
      hashMap.put("schoolName", schoolName);
      return hashMap;
    }).collect(Collectors.toList());
    return mapList;
  }

  @Override
  public List<Map<String, Object>> findCampus() {
    List<Map<String, Object>> schoolList = findSchool();
    List<Map<String, Object>> list = schoolList.stream().map(id -> {
      Map<String, Object> hashMap1 = new HashMap<>();
      String schoolId = (String) id.get("schoolId");
      String schoolName = (String) id.get("schoolName");
      List<Map<String, Object>> mapList = findCampusByPid(schoolId);
      List<Map<String, Object>> mapList1 = mapList.stream().map(a -> {
        String campusId = (String) a.get("id");
        String campusName = (String) a.get("name");
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("campusId", campusId);
        hashMap.put("campusName", campusName);
        hashMap.put("schoolId", schoolId);
        hashMap.put("schoolName", schoolName);
        return hashMap;
      }).collect(Collectors.toList());
      hashMap1.put("schoolId", schoolId);
      hashMap1.put("schoolName", schoolName);
      hashMap1.put("campusList", mapList1);
      return hashMap1;
    }).collect(Collectors.toList());
    return list;
  }

//  定时任务： 每日晚12点更新校区映射关系，并推送到kafka
  @Scheduled(cron = "55 59 20 * * ?")
  //      @Scheduled(cron = "0/50 * * * * ? ")
  public void saveDormitoryMap() {
    if (keyMap) {
      String prefixUrl =
              "http://localhost:13000/api/safe/aggregation/externalData/pushDataDictionary";
      // 设置请求header信息
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_JSON);
      headers.add("Accept", MediaType.ALL_VALUE);
      headers.add(
              "Authorization",
              "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI3MzMyIiwiY29kZSI6InNhZmUtc2Nob29sIiwiZXhwIjoxNjA4MzcwMzk5LCJpYXQiOjE2MDgyODM5OTl9.kpZusqkSrVpMDHt6NPKuvMJDnqlHJI6WdBYuY-Ptwg9pSFZbxEBytWxnrwcnOa197PtSJkjzPWRRhxy9h_rJtQ");
      // 设置请求参数
      Map params = new HashMap<>();
      params.put("type", "schoolAndCampus");
      String data =
              "{\"campusList\":\"校区id与名称集合\",\"schoolId\":\"学校id\",\"schoolName\":\"学校名称\"}";
      params.put("data", data);
      // 封装请求头和内容
      HttpEntity<Map> requestEntity = new HttpEntity<>(params, headers);
      // 发送请求
      ResponseEntity<String> stringResponseEntity =
              restTemplate.postForEntity(prefixUrl, requestEntity, String.class);
      key = false;
    }

    String prefixUrl = "http://localhost:13000/api/safe/aggregation/externalData/pushData";
    // 设置请求header信息
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Accept", MediaType.ALL_VALUE);
    headers.add(
            "Authorization",
            "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI3MzMyIiwiY29kZSI6InNhZmUtc2Nob29sIiwiZXhwIjoxNjA4MzcwMzk5LCJpYXQiOjE2MDgyODM5OTl9.kpZusqkSrVpMDHt6NPKuvMJDnqlHJI6WdBYuY-Ptwg9pSFZbxEBytWxnrwcnOa197PtSJkjzPWRRhxy9h_rJtQ");
    // 设置请求参数
    Map params = new HashMap();
    params.put("type", "schoolAndCampus");
    params.put("typeDescribe", "学校与校区映射表");
    params.put("data", JSON.toJSONString(findCampus()));
    // 封装请求头和内容
    HttpEntity<Map> requestEntity = new HttpEntity<>(params, headers);
    // 发送请求
    ResponseEntity<String> stringResponseEntity =
            restTemplate.postForEntity(prefixUrl, requestEntity, String.class);
  }


  @Override
  public List<Map<String, Object>> findCampusByPid(String pid) {
    String apiUrl = "/eags/api/fas/v1.0/dormitory/search/child";
    if (StringUtil.isEmpty(pid)) {
      throw ServiceSysException.build("id不能为空");
    }
    apiUrl = apiUrl + "?id=" + pid;
    String httpMethod = "GET";
    argsUtil.restTemplateExchange(apiUrl, httpMethod,null);
    HttpHeaders headers = argsUtil.getHeaders();
    HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(null, headers);
    ResponseEntity<Map> responseEntity =
            restTemplate.exchange(
                    argsUtil.getDaHuaConfig().getUrl() + apiUrl, HttpMethod.GET, formEntity, Map.class);
    List<Map<String, Object>> data = (List<Map<String, Object>>) responseEntity.getBody().get("data");
    return data;
  }



  @Override
  public List<Map<String, Object>> findAllDormitoryAttendance() {
    List<Map> data = (List<Map>) getAllDormitory().getBody().get("data");
    Date date = new Date();
//    String queryDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
        String queryDate = "2020-12-22";
    List<Map<String, Object>> mapList =
        data.stream()
            .map(
                id -> {
                  Integer dormitoryId = (Integer) id.get("dormitoryId");
                  String zoneOrgId = (String) id.get("zoneOrgId");
                  String name = (String) id.get("zoneName") + (String) id.get("dormName");
                  Map<String, Object> map =
                      findOneDormitoryAttendance(dormitoryId.longValue(), queryDate);
                  findOneDormitoryAttendance(dormitoryId.longValue(), queryDate);
                  map.put("dormitoryId", dormitoryId);
                  map.put("dormName", name);
                  map.put("date", queryDate);
                  map.put("from", "dormitory");
                  map.put("zoneOrgId", zoneOrgId);
                  return map;
                })
            .collect(Collectors.toList());
        String prefixUrl = "http://localhost:13000/api/safe/aggregation/externalData/pushData";
        // 设置请求header信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Accept", MediaType.ALL_VALUE);
        headers.add(
                "Authorization",
                "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI3MzMyIiwiY29kZSI6InNhZmUtc2Nob29sIiwiZXhwIjoxNjA4NzczNTM2LCJpYXQiOjE2MDg2ODcxMzZ9.V5J8H_tUr_8iVJR39ChXm69qwVVDiwgRTyj7Oyqi6sV8ML_GoHjYmojBp1PPEuViRVZj14SPixqVwNx9GFt3Pw");
        // 设置请求参数
        Map params = new HashMap();
        params.put("type", "dormitoryAttendance");
        params.put("typeDescribe", "宿舍楼考勤统计数据");
        params.put("data", JSON.toJSONString(mapList));
        // 封装请求头和内容
        HttpEntity<Map> requestEntity = new HttpEntity<>(params, headers);
        // 发送请求
        ResponseEntity<String> stringResponseEntity =
                restTemplate.postForEntity(prefixUrl, requestEntity, String.class);
    return mapList;
  }

  @Override
  public Map<String, Object> findOneDormitoryAttendance(Long dormitoryId, String queryDate) {
    String apiUrl = "/eags/api/fas/v1.0/getDormitoryAttendance";
    if (Objects.isNull(dormitoryId) && StringUtil.isEmpty(queryDate)) {
      throw ServiceSysException.build("宿舍id和查询日期不能为空");
    }
    apiUrl = apiUrl + "?dormitoryId=" + dormitoryId + "&date=" + queryDate;
    String httpMethod = "GET";
    argsUtil.restTemplateExchange(apiUrl, httpMethod,null);
    HttpHeaders headers = argsUtil.getHeaders();
    HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(null, headers);
    ResponseEntity<Map> responseEntity =
        restTemplate.exchange(
            argsUtil.getDaHuaConfig().getUrl() + apiUrl, HttpMethod.GET, formEntity, Map.class);
    Map<String, Object> data = (Map<String, Object>) responseEntity.getBody().get("data");
    return data;
  }

  @Override
  public Object findDormitory() {

    String id = "";
    String name = "";
    String pId = "";
    int level = 2;
    String apiUrl =
        "/eags/api/fas/v1.0/dormitory/search?"
            + "id="
            + id
            + "&name="
            + name
            + "&pid="
            + pId
            + "&level="
            + level;
    String httpMethod = "GET";
    argsUtil.restTemplateExchange(apiUrl, httpMethod,null);
    HttpHeaders headers = argsUtil.getHeaders();
    HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(null, headers);
    ResponseEntity<String> responseEntity =
        restTemplate.exchange(
            argsUtil.getDaHuaConfig().getUrl() + apiUrl, HttpMethod.GET, formEntity, String.class);
    return responseEntity;
  }

  @Override
  public ResponseEntity<Map> findDormitoryByName() {
    String name = "";
    String apiUrl = "/eags/api/fas/v1.0/dormitory/search/name?" + "name=" + name;
    String httpMethod = "GET";
    argsUtil.restTemplateExchange(apiUrl, httpMethod,null);
    HttpHeaders headers = argsUtil.getHeaders();
    HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(null, headers);
    ResponseEntity<Map> responseEntity =
        restTemplate.exchange(
            argsUtil.getDaHuaConfig().getUrl() + apiUrl, HttpMethod.GET, formEntity, Map.class);
    return responseEntity;
  }

  @Override
  public ResponseEntity<Map> getAllDormitory() {
    String apiUrl = "/eags/api/fas/v1.0/getAllDormitory";
    String httpMethod = "GET";
    argsUtil.restTemplateExchange(apiUrl, httpMethod,null);
    HttpHeaders headers = argsUtil.getHeaders();
    HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(null, headers);
    ResponseEntity<Map> responseEntity =
        restTemplate.exchange(
            argsUtil.getDaHuaConfig().getUrl() + apiUrl, HttpMethod.GET, formEntity, Map.class);
    return responseEntity;
  }

  /** 定时任务： 每日晚12点获取当日考勤数据，并推送到kafka */
  @Scheduled(cron = "55 59 23 * * ?")
  //      @Scheduled(cron = "0/50 * * * * ? ")
  public void saveDormitoryAttendance() {
    if (key) {
      String prefixUrl =
          "http://localhost:13000/api/safe/aggregation/externalData/pushDataDictionary";
      // 设置请求header信息
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_JSON);
      headers.add("Accept", MediaType.ALL_VALUE);
      headers.add(
          "Authorization",
          "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI3MzMyIiwiY29kZSI6InNhZmUtc2Nob29sIiwiZXhwIjoxNjA4NzczNTM2LCJpYXQiOjE2MDg2ODcxMzZ9.V5J8H_tUr_8iVJR39ChXm69qwVVDiwgRTyj7Oyqi6sV8ML_GoHjYmojBp1PPEuViRVZj14SPixqVwNx9GFt3Pw");
      // 设置请求参数
      Map params = new HashMap<>();
      params.put("type", "dormitoryAttendance");
      String data =
          "{\"dormitoryId\":\"宿舍楼id\",\"dormName\":\"宿舍楼名称\",\"date\":\"查询时间\",\"normalAttendance\":\"在寝室人数\",\"lateAttendance\":\"晚归人数\",\"totalAttendance\":\"寝室总人数\",\"notBackAttendance\":\"未归人数\"}";
      params.put("data", data);
      // 封装请求头和内容
      HttpEntity<Map> requestEntity = new HttpEntity<>(params, headers);
      // 发送请求
      ResponseEntity<String> stringResponseEntity =
          restTemplate.postForEntity(prefixUrl, requestEntity, String.class);
      key = false;
    }
    List<Map> data = (List<Map>) getAllDormitory().getBody().get("data");
    Date date = new Date();
    String queryDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
    List<Map<String, Object>> mapList =
        data.stream()
            .map(
                id -> {
                  Integer dormitoryId = (Integer) id.get("dormitoryId");
                  String zoneOrgId = (String) id.get("zoneOrgId");
                  String name = (String) id.get("zoneName") + (String) id.get("dormName");
                  Map<String, Object> map =
                      findOneDormitoryAttendance(dormitoryId.longValue(), queryDate);
                  findOneDormitoryAttendance(dormitoryId.longValue(), queryDate);
                  map.put("dormitoryId", dormitoryId);
                  map.put("dormName", name);
                  map.put("date", queryDate);
                  map.put("from", "dormitory");
                  map.put("zoneOrgId", zoneOrgId);
                  return map;
                })
            .collect(Collectors.toList());

    String prefixUrl = "http://localhost:13000/api/safe/aggregation/externalData/pushData";
    // 设置请求header信息
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Accept", MediaType.ALL_VALUE);
    headers.add(
        "Authorization",
        "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI3MzMyIiwiY29kZSI6InNhZmUtc2Nob29sIiwiZXhwIjoxNjA4MzcwMzk5LCJpYXQiOjE2MDgyODM5OTl9.kpZusqkSrVpMDHt6NPKuvMJDnqlHJI6WdBYuY-Ptwg9pSFZbxEBytWxnrwcnOa197PtSJkjzPWRRhxy9h_rJtQ");
    // 设置请求参数
    Map params = new HashMap();
    params.put("type", "dormitoryAttendance");
    params.put("typeDescribe", "宿舍楼考勤统计数据");
    params.put("data", JSON.toJSONString(mapList));
    // 封装请求头和内容
    HttpEntity<Map> requestEntity = new HttpEntity<>(params, headers);
    // 发送请求
    ResponseEntity<String> stringResponseEntity =
        restTemplate.postForEntity(prefixUrl, requestEntity, String.class);
  }
}
